package com.csun.dsms.controller;

import com.csun.dsms.comment.config.properties.CsunProperties;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.DsmsResource;
import com.csun.dsms.model.domain.DsmsUser;
import com.csun.dsms.service.DsmsResourceService;
import com.csun.dsms.utils.DateUtil;
import com.csun.dsms.utils.MimeTypeUtil;
import com.csun.dsms.utils.OSSManageUtil;
import com.csun.dsms.utils.SourceType;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-01 19:47
 * @description: 资源管理拦截器
 */
@RestController
@RequestMapping("/resource")
public class DsmsResourceController {

    @Resource
    private DsmsResourceService dsmsResourceService;
    @Resource
    private OSSManageUtil ossManageUtil;
    @Resource
    private CsunProperties csunProperties;

    /**
     * 资源文件上传
     *
     * @param login     the login user
     * @param response  the http servlet response
     * @param request   the http servlet request
     *
     * @throws Throwable    the throwable
     */
    @Authorization
    @RequestMapping(value="/upload",method= RequestMethod.POST,produces="application/json")
    public Wrapper upload(@CurrentUser DsmsUser login, HttpServletResponse response,
                          HttpServletRequest request) throws Throwable {
        /* 获取文件描述参数 */
        String remark = request.getParameter("remark");

        List<DsmsResource> resources = new ArrayList<DsmsResource>();

        /* 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）*/
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());

        /* 检查form中是否有enctype="multipart/form-data" */
        if(multipartResolver.isMultipart(request)) {
            /* 将request变成多部分request */
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

            /* 获取multiRequest 中所有的文件名*/
            Iterator iter=multiRequest.getFileNames();
            String timedate  = DateUtil.getOrderNum();	// 时间戳,避免文件覆盖

            while(iter.hasNext()) {

                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if(file != null) {

                    /* 文件属性获取 */
                    SourceType sourceType = MimeTypeUtil.getSourceType(file.getContentType());

                    /* MultipartFile 转 File */
                    File f=File.createTempFile("tmp", null);
                    file.transferTo(f);
                    f.deleteOnExit();
                    /* OSS文件上传 */
                    ossManageUtil.uploadFile(f, file.getOriginalFilename(), file.getContentType(), sourceType
                                    .getSourceTypePath() + "/" + timedate);
                    /* 保存上传的文件属性 */
                    DsmsResource r = new DsmsResource();
                    r.setResourceName(file.getOriginalFilename());
                    r.setResourcePath(csunProperties.getAliyun().getOss().getAccessUrl() + "/"
                            + sourceType.getSourceTypePath() + "/" + timedate + "/" + file.getOriginalFilename());
                    if (StringUtils.isNotBlank(remark)) {
                        r.setRemark(remark);
                    }
                    r.setResourceTypeId(Integer.parseInt(sourceType.getSourceTypeId()));
                    r.setUpdateInfo(login);
                    // 添加资源记录
                    dsmsResourceService.save(r);

                    resources.add(r);
                }
            }
        }

        return WrapMapper.ok(resources);

//        /* 返回上传结果 */
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json");
//        /* 解决文件上传跨域问题 */
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//        // 默认只上传了一个文件
//        JSONObject jsObject = JSONObject.fromObject(new JsonResult(true, "文件上传成功", resources));
//
//        response.getWriter().write(jsObject.toString());
    }

}
